package com.qyc.utils;

import com.qyc.enums.CodeMsgEnum;
import com.qyc.exception.SystemException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @className: UploadUtils
 * @Description: 文件上传工具类
 * @author: qinyc
 * @date: 2023/6/23 21:59
 * @version: v1.0
 */
@Component
@ConfigurationProperties(prefix = "image")
public class UploadUtil {
    //图片路径
    private static String path;
    private static String server;



    public void setPath(String path) {
        UploadUtil.path = path;
    }

    public void setServer(String server) {
        UploadUtil.server = server;
    }



    public static String upload(MultipartFile file){
        try {
            //1.获取文件名字
            String filename = file.getOriginalFilename();
            //防止上传文件名重复导致覆盖文件（使用UUID工具类生成文件名）
            String id = UUID.randomUUID().toString();
            //文件名前面拼接UUID,并将UUID与文件名之间使用“-”分割
            filename = String.join("-",id,filename);
            //2.保存文件到本地磁盘
            file.transferTo(new File(path,filename));
            //3.返回访问文件服务器的访问url
            String filepath = server + filename;
            return filepath;
        } catch (Exception e) {
            //打印日志
            e.printStackTrace();
            //自定义异常信息，文件上传失败
            throw new SystemException(CodeMsgEnum.UPLOAD_ERROR);
        }
    }
}
